<?php
session_start();
include('../include/util.inc.php');
$PDO = getPDO();
$first_sql_section = true;

function composite_sql_with_and($sql){
    global $first_sql_section;
    if($first_sql_section){
        $first_sql_section = false;
    }else{
        $sql = $sql . " and";
    }
    return $sql;
}
function composite_sql($str, $sql){
    global $PDO;
    global $first_sql_section;
    if($str == 'property'){
        if(isset($_GET['property'])){
            $property = intval($_GET['property']);
            if($property == 0){
                $sql = composite_sql_with_and($sql);
                $tmp = 0;
                $sql = $sql . " `$str` = $tmp";
            }else if($property == 1){
                $sql = composite_sql_with_and($sql);
                $tmp = $_SESSION['uid'];
                $sql = $sql . " `$str` = $tmp";
            }else{
                $sql = composite_sql_with_and($sql);
                $tmp = $_SESSION['uid'];
                $sql = $sql . " (`$str` = 0 or `$str` = $tmp)";
            }
        }
    }else if($str == 'tag' && isset($_GET['tag'])){
        $sql = composite_sql_with_and($sql);
        $tmp = $PDO->quote('%'.$_GET[$str].'%');
        $sql = $sql . " (`answer` LIKE $tmp or `question` LIKE $tmp)";
    }else if(isset($_GET[$str])){
        $sql = composite_sql_with_and($sql);
        $tmp = $PDO->quote($_GET[$str]);
        $sql = $sql . " `$str` = $tmp";
    }
    return $sql;
}


$sql = "SELECT * FROM question WHERE";
$sql = composite_sql('category', $sql);
$sql = composite_sql('level', $sql);
$sql = composite_sql('tag', $sql);
$sql = composite_sql('property', $sql);


if($first_sql_section){
    $sql = str_replace('WHERE', '', $sql);
}

// echo $sql;

try{
    $result = $PDO->query($sql);
    $result = $result->fetchAll();
    $res = ['total' => count($result), 'detail' => $result];
    echo json_encode( $res );
}catch (\PDOException $e) {
    echo $e->getMessage();
}

?>